package com.bai.ruiji.Service.impl;

import com.bai.ruiji.Common.CustomException;
import com.bai.ruiji.Common.R;
import com.bai.ruiji.Service.SetmealDishService;
import com.bai.ruiji.Service.SetmealService;
import com.bai.ruiji.mapper.SetmealMapper;
import com.bai.ruiji.pojo.Setmeal;
import com.bai.ruiji.pojo.SetmealDish;
import com.bai.ruiji.pojo.SetmealDto;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 27471
 * Time : 2022/10/10 17:35
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐同时保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Transactional//事务注解
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息setmeal表insert操作
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐和菜品的关联信息setmeal_dish执行insert操作
        setmealDishService.saveBatch(setmealDishes);

    }

    /**
     * 删除套餐同时删除套餐和菜品的关联数据
     * @param ids
     */
    @Transactional//事务注解
    @Override
    public void removeWithDish(List<Long> ids) {
        //select count(*)  from setmeal where id in (1,2) and status=1
        //查询套餐的状态，是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);
        if (count>0){
            //如果不能删除，抛出异常
            throw  new CustomException("套餐正在售卖中，请先停售再删除");
        }
        //如果可以删除，删除套餐表中的数据
        this.removeByIds(ids);

        //删除关系表中的数据
        //delete from setmeal_dish where setmeal_id in(1,2)
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(dishLambdaQueryWrapper);
    }

}
